package com.alpha.provider.service;

import com.alpha.provider.mapper.StudentDao;
import com.alpha.provider.pojo.Student;
import com.alpha.provider.util.RedisUtil;
import com.codingapi.txlcn.tc.annotation.DTXPropagation;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author YDF
 * @version 1.0.0
 * @Description 提供方接口
 * @createTime 2020年08月19日 14:47:00
 */
@Service
public class StudentServiceImpl implements StudentService {
	@Autowired
	private StudentDao studentDao;
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public int deleteByPrimaryKey(Integer id) {
		return studentDao.deleteByPrimaryKey(id);
	}
	
	@LcnTransaction(propagation = DTXPropagation.SUPPORTS) //分布式事务注解(参与方)
	@Transactional(rollbackFor = Exception.class) //本地事务注解
	@Override
	public int insert(Student record) {
		studentDao.insert(record);
//		rollBack();
		redisUtil.set("feign:"+record.getId(), record);
		return record.getId();
	}
	
	@Override
	public int insertSelective(Student record) {
		return studentDao.insertSelective(record);
	}
	
	@Override
	public Student selectByPrimaryKey(Integer id) {
		return studentDao.selectByPrimaryKey(id);
	}
	
	@LcnTransaction(propagation = DTXPropagation.SUPPORTS) //分布式事务注解(参与方)
	@Transactional(rollbackFor = Exception.class) //本地事务注解
	@Override
	public int updateByPrimaryKeySelective(Student record) {
		int row = studentDao.updateByPrimaryKeySelective(record);
//		rollBack();
		return row;
	}
	
	/**
	 * @Description： 回滚
	 * @Author： YDF
	 * @Date： 2020/11/6 0006
	 */
	private void rollBack(){
		//1. 单个服务回滚，必须要有@Transactional标注（手动回滚）
//		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		//2.分布式事务回滚，要求所有被调用的三方接口必须有@LcnTransaction（手动回滚）,亲测可用
//		DTXUserControls.rollbackCurrentGroup();
		//3.直接抛错也会自动回滚事务
		int a = 1/0;//模拟异常
	}
	
	@Override
	public int updateByPrimaryKey(Student record) {
		return studentDao.updateByPrimaryKey(record);
	}
}
